<?php

/**
 * 账户充值
 */

namespace app\member\api;


class RechargeApi extends \app\member\api\MemberApi {

    public function index() {
        $type = $this->data['type'];
        $money = price_format($type->data['money']);

        if(empty($type)) {
            $this->error('请选择支付方式!');
        }
        if($money <= 0) {
            $this->error('充值金额错误!');
        }
        $payList = target('member/PayConfig')->typeList();
        $payTypeInfo = $payList[$type];
        if (empty($payTypeInfo)) {
            $this->error('该支付类型不存在!');
        }
        if ($payTypeInfo['platform'] <> 'api') {
            $this->error('该支付类型无法使用!');
        }

        $logNo = target('member/Finance', 'service')->logNo($this->userId);
        $config = \Config::get('dux.use');

        $model = target('member/MemberRecharge');
        $model->beginTransaction();
        $data = [];
        $data['user_id'] = $this->userId;
        $data['money'] = $money;
        $data['recharge_no'] = $logNo;
        $data['status'] = 0;
        $data['create_time'] = time();
        if(!target('member/MemberRecharge')->add($data)) {
            $model->rollBack();
            $this->error('充值订单创建失败!');
        }

        $data = target($payTypeInfo['target'], 'pay')->getData([
            'user_id' => $this->userId,
            'order_no' => $logNo,
            'money' => $money,
            'title' => '会员充值',
            'body' => '会员充值',
            'url' => url('member/Recharge/pay'),
            'app' => 'member',
        ]);

        if (!$data) {
            $model->rollBack();
            $this->error(target($payTypeInfo['target'], 'pay')->getError());
        }
        $model->commit();
        $this->success($data);

    }

    public  function log() {

        $pageLimit = $this->data['limit'] ? $this->data['limit'] : 10;

        $where = [];

        $where['A.user_id'] = $this->userId;

        $model = target('member/MemberRecharge');
        $count = $model->countList($where);
        $pageData = $this->pageData($count, $pageLimit);
        $list = $model->loadList($where, $pageData['limit'], 'recharge_id desc');

        if ($list) {
            $this->success('ok', [
                'data' => $list,
                'pageData' => [
                    'pageLimit' => $pageLimit,
                    'limit' => count($list),
                    'page' => $pageData['page'],
                    'totalPage' => $pageData['totalPage']
                ]
            ]);
        } else {
            $this->error('暂无更多记录', 404);
        }

    }

}